package yaq.mini.weibo.leafwb.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import yaq.mini.weibo.leafwb.pojo.Article;
import yaq.mini.weibo.leafwb.pojo.User;
import yaq.mini.weibo.leafwb.service.ArticleService;
import yaq.mini.weibo.leafwb.service.FavouriteCollectionService;
import yaq.mini.weibo.leafwb.service.UserService;
import yaq.mini.weibo.leafwb.util.VerifyUtil;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class MainController {
    @Resource
    private UserService userService;
    @Resource
    private ArticleService articleService;
    @Resource
    private FavouriteCollectionService favouriteCollectionService;

    /**
     * 初始页面，也为游客可登录的界面
     *
     * @return ModelAndView
     */
    @RequestMapping(method = RequestMethod.GET, value = "/")
    public ModelAndView initPage(HttpServletRequest request) {
        List<Article> articleList = articleService.listArticles();
        List<Article> hotArticleList = getHotTopic(articleList);
        List<Article> newestArticleList = articleService.getNewestArticle(5);
        Map<String, Object> map = new HashMap<>();
        map.put("articleList", articleList);
        map.put("hotArticleList", hotArticleList);
        map.put("newestArticleList", newestArticleList);
        map.put("userId1", getValueByCookieName("userName", request));
        map.put("userId2", getValueByCookieName("userName", request));
        map.put("password", getValueByCookieName("password", request));
        ModelAndView mv = new ModelAndView("index", map);
        return mv;
    }

    @RequestMapping("/register")
    @ResponseBody
    public Map<String, String> handelRegister(User user) {
        user.setIsAllowShare("T");
        Random ran = new Random();
        user.setName("undefine" + ran.nextInt(99999 - 10000 + 1) + 10000);
        //注册时间
        Date registerDate = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        user.setRegisterDate(dateFormat.format(registerDate));
        //初始头像
        user.setHeadPictureUrl("D:/MyFiles/MyPicture/MyProjectPic/head/initHeadPic.png");
        Map<String, String> model = new HashMap<>();
        if (!userService.insertUserByRegister(user)) {
            model.put("warnMsg", "该手机号码已注册，请查看号码是否输入正确或者选择忘记密码");
        } else {
            model.put("warnMsg", "注册成功，可以进行登录啦！！");
        }
        return model;
    }

    /**
     * 处理登录的信息
     *
     * @param userId
     * @param password
     * @return
     */
    @RequestMapping("/login")
    @ResponseBody
    public Map<String,Boolean> handleLoginByArticleDetail(String userId, String password, String captcha, boolean check, HttpServletResponse response, HttpSession session) {
        Map<String,Boolean> map=new HashMap<>();
        //得到验证码
        String imageCode = (String) session.getAttribute("imageCode");
        boolean isLogin=false;
        if(!imageCode.equals(captcha)){
            map.put("isCaptcha",false);
        }else{
            map.put("isCaptcha",true);
            isLogin=userService.isUserExit(userId, password);
        }
        map.put("isLogin",isLogin);
        if (isLogin) {
            //用cookie保存数据
            Cookie cookie = new Cookie("userId", userId);
            cookie.setMaxAge(60 * 60 * 6);//这里设置设置有效时间，单位的秒，我这里是六小时
            //cookie.setMaxAge(60);
            cookie.setPath("/");//这里是之根目录下所有的目录都可以共享Cookie
            response.addCookie(cookie);
            if (check) {
                Cookie ucookie = new Cookie("userName", userId);
                Cookie pcookie = new Cookie("password", password);
                ucookie.setMaxAge(60 * 60 * 24 * 7);//有效时间为7天
                pcookie.setMaxAge(60 * 60 * 24 * 7);
                response.addCookie(ucookie);
                response.addCookie(pcookie);
            }
        }
        return map;
    }

    @RequestMapping("/in/home")
    public ModelAndView home(int leftNav, HttpServletRequest request) {
        String userId = getValueByCookieName("userId", request);
        if (userId.length() == 0)
            return new ModelAndView("autoJumpAround");
        Map<String, Object> map = new HashMap<>();
        User user = userService.getUserByLogin(userId);
        List<Article> articleList = null;
        List<String> likerList = favouriteCollectionService.listArticleIdByLike(userId);
        List<String> collectorList = favouriteCollectionService.listArticleIdByCollect(userId);
        List<String> shieldList = favouriteCollectionService.listArticleIdByShield(userId);
        if (leftNav == 1) {
            articleList = articleService.listArticlesOrderByTime();
        } else if (leftNav == 2) {
            articleList = articleService.listArticlesByID(collectorList);
        } else if (leftNav == 3) {
            articleList = articleService.listArticlesByID(likerList);
        } else if (leftNav == 4) {
            articleList = articleService.listArticlesByUserID(userId);
        } else if (leftNav == 10086) {
            map.put("userList", userService.listUserExceptRoot());
        } else if (leftNav == 1008611) {
            map.put("keywordList", articleService.listKeyword());
        }

        map.put("user", user);
        map.put("leftNav", leftNav);
        map.put("articleList", articleList);
        map.put("likerList", likerList);
        map.put("collectorList", collectorList);
        map.put("shieldList", shieldList);
        ModelAndView mv = new ModelAndView("in/home", map);
        return mv;
    }

    @RequestMapping("/in/logout")
    public String logout(HttpServletRequest request, HttpServletResponse response) {
        request.getSession().invalidate();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("userId".equalsIgnoreCase(cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                    break;
                }
            }
        }
        return "redirect:/";
    }

    @RequestMapping("/in/out")
    public String outByLoginTime() {
        return "autoJumpAround";
    }

    @GetMapping("/getCode")
    public void getCode(HttpServletResponse response, HttpSession session) throws Exception {
        //利用图片工具生成图片
        //第一个参数是生成的验证码，第二个参数是生成的图片
        Object[] objs = VerifyUtil.createImage();
        //将验证码存入Session
        session.setAttribute("imageCode", objs[0]);

        //将图片输出给浏览器
        BufferedImage image = (BufferedImage) objs[1];
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
    }

    /**
     * 得到输入的文章列表里点赞最多的前七篇所有人可见的文章
     *
     * @param articleList
     * @return
     */
    public List<Article> getHotTopic(List<Article> articleList) {
        List<Article> hotTopicArticleList = new ArrayList<>();
        int i = 0;
        while (i < articleList.size()) {
            if (articleList.get(i).getAuthority() == 0) {
                hotTopicArticleList.add(articleList.get(i));
                break;
            }
            i++;
        }
        for (i = i + 1; i < articleList.size(); i++) {
            if (articleList.get(i).getAuthority() == 1)
                continue;
            int n = (hotTopicArticleList.size() > 7 ? 7 : hotTopicArticleList.size());
            Long aLikeNum = articleList.get(i).getLikeNum();
            Long aCommentNum = articleList.get(i).getCommentCount();
            for (int j = 0; j < n; j++) {
                Long bLikeNum = hotTopicArticleList.get(j).getLikeNum();
                Long bCommendNum = hotTopicArticleList.get(j).getCommentCount();
                if ((aLikeNum > bLikeNum) || (aLikeNum == bLikeNum && aCommentNum > bCommendNum)) {
                    hotTopicArticleList.add(j, articleList.get(i));
                    break;
                }
                if ((j == n - 1) && n < 7)
                    hotTopicArticleList.add(n, articleList.get(i));
            }
        }
        return hotTopicArticleList;
    }

    public static String getValueByCookieName(String cookieName, HttpServletRequest request) {
        String value = "";
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookieName.equalsIgnoreCase(cookie.getName())) {
                    value = cookie.getValue();
                    break;
                }
            }
        }
        return value;
    }

}